package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.TongChengJieParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Map;

@Service
public class TongChengJieReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String rsaSecret = sourceBaseInfo.getPriKey();//RSA私钥

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }

        String content = jsonObjectParamContent.getString("content");
        String key = jsonObjectParamContent.getString("key");
        String channelCode = jsonObjectParamContent.getString("channelCode");
        String applyNo = jsonObjectParamContent.getString("applyNo");//请求流水号

        String aesSecret = null;
        try {
            aesSecret = SecureUtil.rsa(rsaSecret, null).decryptStr(key, KeyType.PrivateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String paramContentData = SecureUtil.aes(aesSecret.getBytes()).decryptStr(content);

        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("channelId")) || StrUtil.isEmpty(jsonObject.getString("phoneMd5")) || StrUtil.isEmpty(jsonObject.getString("userName")) || jsonObject.getInteger("age") == null || jsonObject.getInteger("sex") == null || jsonObject.getInteger("professIdentity") == null || StrUtil.isEmpty(jsonObject.getString("city")) || StrUtil.isEmpty(jsonObject.getString("cityCode")) || jsonObject.getInteger("zhimaCredit") == null || jsonObject.getInteger("fund") == null || jsonObject.getInteger("creditCard") == null || jsonObject.getInteger("has") == null || jsonObject.getInteger("bdStatus") == null || jsonObject.getInteger("carProperty") == null || jsonObject.getInteger("houseProperty") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        JSONObject jsonObject1 = JSONObject.parseObject(paramContentData);
        jsonObject1.put("applyNo",applyNo);
        String paramContentData1 = JSON.toJSONString(jsonObject1);
        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());
        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String rsaSecret = sourceBaseInfo.getPriKey();//RSA私钥

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }

        String content = jsonObjectParamContent.getString("content");
        String key = jsonObjectParamContent.getString("key");
        String channelCode = jsonObjectParamContent.getString("channelCode");
        String applyNo = jsonObjectParamContent.getString("applyNo");//请求流水号

        String aesSecret = null;
        try {
            aesSecret = SecureUtil.rsa(rsaSecret, null).decryptStr(key, KeyType.PrivateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String paramContentData = SecureUtil.aes(aesSecret.getBytes()).decryptStr(content);

        JSONObject jsonObject1 = JSONObject.parseObject(paramContentData);
        jsonObject1.put("applyNo",applyNo);
        String paramContentData1 = JSON.toJSONString(jsonObject1);

        TongChengJieParam tongChengJieParam = JSON.parseObject(paramContentData1, TongChengJieParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData1);

        userDataParam.setMobile(tongChengJieParam.getPhone());
        userDataParam.setRealName(tongChengJieParam.getUserName());

        String applyNo1 = tongChengJieParam.getApplyNo();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), applyNo1);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();
        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code",0);
        returnObject.put("msg", "匹配成功！");
        JSONObject dataJson = new JSONObject();

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())) {
            // 下游是 非 apis 类型
            dataJson.put("productName", thirdBaseInfo.getProductName());
            dataJson.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataJson.put("logo", "");
            }else {
                dataJson.put("logo", companyLogo);
            }
        }else {
            dataJson.put("productName", merchantBaseInfo.getInfoName());
            dataJson.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataJson.put("logo", "");
            }else {
                dataJson.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            //协议地址
//        JSONArray jsonArray = new JSONArray();
//        JSONObject jsonObject = new JSONObject();
//        ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
//        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
//        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
//        jsonObject.put("contractName","授权协议");
//        jsonObject.put("contractUrl", protocolUrl);
//        jsonArray.add(jsonObject);
//        dataJson.put("contractList", jsonArray);
        }
        returnObject.put("data",dataJson);

        sourceApiResult.setReturnObject(returnObject);


        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code",1);
        returnObject.put("message", message);
        JSONObject dataJson = new JSONObject();
        returnObject.put("data",dataJson);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code",0);
        returnObject.put("message", "推送成功！");
        JSONObject dataJson = new JSONObject();
        returnObject.put("data",dataJson);
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        TongChengJieParam tongChengJieParam = JSON.parseObject(paramContent, TongChengJieParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setOutOrderNo(tongChengJieParam.getApplyNo());

        userDataParam.setMobileMd5(tongChengJieParam.getPhoneMd5());
        userDataParam.setMobile(tongChengJieParam.getPhone());
        userDataParam.setRealName(tongChengJieParam.getUserName());
        userDataParam.setAge(tongChengJieParam.getAge());
        userDataParam.setSex(String.valueOf(tongChengJieParam.getSex()));
        userDataParam.setCityCode(tongChengJieParam.getCityCode());

        Integer professIdentity = tongChengJieParam.getProfessIdentity();
        if (professIdentity == null){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else {
            if ("0".equals(String.valueOf(professIdentity))){
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
            }else if ("1".equals(String.valueOf(professIdentity)) || "2".equals(String.valueOf(professIdentity))){
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
            }else if ("3".equals(String.valueOf(professIdentity))){
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
            }else if ("5".equals(String.valueOf(professIdentity))){
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
            }else {
                userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
            }
        }

        Integer zhimaCredit = tongChengJieParam.getZhimaCredit();
        if (zhimaCredit == null){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }else {
            if (zhimaCredit == 5){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
            }else if (zhimaCredit == 4){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
            }else if (zhimaCredit == 3){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
            }else if (zhimaCredit == 2){
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
            }else{
                userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
            }
        }

        Integer fund = tongChengJieParam.getFund();
        if (fund == null){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else {
            if ("2".equals(String.valueOf(fund))){
                userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
            }else if ("1".equals(String.valueOf(fund))){
                userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
            }else {
                userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
            }
        }

        Integer creditCard = tongChengJieParam.getCreditCard();
        if (creditCard == null){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            if ("3".equals(String.valueOf(fund))){
                userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
            }else {
                userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk004.getValue());
            }
        }

        Integer hasSocial = tongChengJieParam.getHas();
        if (hasSocial == null){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else {
            if ("0".equals(String.valueOf(hasSocial))){
                userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
            }else if ("2".equals(String.valueOf(hasSocial))){
                userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
            }else {
                userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
            }
        }

        Integer hasInsurance = tongChengJieParam.getBdStatus();
        if (hasInsurance == null){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            if ("2".equals(String.valueOf(hasInsurance))){
                userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
            }else if ("0".equals(String.valueOf(hasInsurance))){
                userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
            }else {
                userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());
            }
        }

        Integer hasCar = tongChengJieParam.getCarProperty();
        if (hasCar == null){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else {
            if ("2".equals(String.valueOf(hasCar))){
                userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
            }else if ("1".equals(String.valueOf(hasCar))){
                userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
            }else {
                userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
            }
        }

        Integer houseProperty = tongChengJieParam.getHouseProperty();
        if (houseProperty == null){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            if ("2".equals(String.valueOf(houseProperty))){
                userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
            }else if ("1".equals(String.valueOf(houseProperty))){
                userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
            }else {
                userDataParam.setHouse(BaseTypeInfoEnum.House.hu004.getValue());
            }
        }

        String loanAmount = tongChengJieParam.getLoanAmount();
        if (StringUtils.isEmpty(loanAmount)){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        }else {
            if (Integer.valueOf(loanAmount) <= 30000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
            } else if (Integer.valueOf(loanAmount) > 30000 && Integer.valueOf(loanAmount) <= 50000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
            } else if (Integer.valueOf(loanAmount) > 50000 && Integer.valueOf(loanAmount) <= 100000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
            } else if (Integer.valueOf(loanAmount) >100000 && Integer.valueOf(loanAmount) <= 200000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
            } else {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
            }
        }

        String registerIp = tongChengJieParam.getRegisterIp();
        if (StringUtils.isEmpty(registerIp)){
            userDataParam.setUserIp("127.0.0.1");
        }else{
            userDataParam.setUserIp(tongChengJieParam.getRegisterIp());
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());

        return userDataParam;
    }


    /**
     * 解密aesKey原文
     *
     * @param encryptedKey 加密的aesKey
     * @param privateRSAKey rsa私钥
     * @return String
     * @throws Exception
     */
    public static String decryptKey(String encryptedKey, String privateRSAKey) throws Exception {
        byte[] privateKeyData = Base64.getDecoder().decode(privateRSAKey);
        byte[] encryptedAESKey = Base64.getDecoder().decode(encryptedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyData));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedAESKey = cipher.doFinal(encryptedAESKey);
        return Base64.getEncoder().encodeToString(decryptedAESKey);
    }






}
